package rak.r91.controller;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import rak.r91.data.User;
import rak.r91.service.AuthenticationService;


@Controller
@RequestMapping("/login")
@SessionAttributes("user")
public class LoginController{
	protected final Log logger = LogFactory.getLog(getClass());
	
	@RequestMapping(method=RequestMethod.GET)
    public ModelAndView loginPage(HttpServletRequest request, HttpServletResponse response) throws Exception {
		if(request.getSession() != null){
			logger.info("Login controller: Change wiev to index");
			return new ModelAndView("index");
		}else{
			logger.info("Login controller: Change wiev to login");
			return new ModelAndView("login");
		}
    }
    
    @RequestMapping(method=RequestMethod.POST)
    public ModelAndView loginRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String username = request.getParameter("username");
        String password = request.getParameter("password");       
    	if(username != null && password != null ){
    		User user = new AuthenticationService().authenticate(username, password);
    		if(user != null){
    			System.out.println("authentucated");
    			//request.setAttribute("username", username);
    			ModelAndView mav = new ModelAndView("index");
    			mav.addObject(user);
    			logger.info("Login controller: Change wiev to index");
    			return mav;
    		}else{
    			logger.info("Login controller: Change wiev to login");
    			return new ModelAndView("login");
    		}
    	}else
    		logger.info("Login controller: Change wiev to login");
    		return new ModelAndView("login");
    }
    

}
